package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.model.behavior.dtos.CollectionBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.index.qual.SameLen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 收藏 行为操作
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectBehavior(CollectionBehaviorDTO dto) {

        //根据userid 查询行为实体数据
        ApUser user = AppThreadLocalUtils.getUser();
        //查询 行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());

        //如果是收藏操作 判断是否已经收藏  为0的话 就是收藏操作
        //先查询 有没有 对应的数据
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApCollection one = mongoTemplate.findOne(query, ApCollection.class);
        if(dto.getOperation().equals(ApCollection.Type.ARTICLE.getCode())){
            if(one == null){
                //如果查询不到数据 就认为没有 则创建
                ApCollection apCollection = new ApCollection();
                apCollection.setEntryId(apBehaviorEntry.getId());
                apCollection.setArticleId(dto.getArticleId());
                apCollection.setType(dto.getType());
                apCollection.setCollectionTime(new Date());
                ApCollection save = mongoTemplate.save(apCollection);
                log.info("收藏行为以操作成功 返回结果为:{}",save);
            }
        }else if(dto.getOperation().equals(ApCollection.Type.DYNAMIC.getCode())){
            DeleteResult remove = mongoTemplate.remove(query, ApCollection.class);
            log.info("取消收藏行为以操作成功 返回结果为:{}",remove);
        }
        return ResponseResult.okResult();
    }
}
